<script setup>
import {onMounted,ref} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from 'qs';
import axios from "axios";
const user = ref(localStorage.user?JSON.parse(localStorage.user):null);
const weibo = ref({
  content:"",
    userId:"",
})
weibo.value.userId = user.value.id;

onMounted(()=>{
  if(user.value==null) {
      ElMessage.error("请先登录账号");
      router.push("/login");
  }
})

const post = ()=>{
  //将fileList数组中的数据存入imgUrls

 if(fileList.value.length>0) {
   let imgUrls = [];//准备空数组,用来存多个图片路径
   for (let file of fileList.value) {
     let imgUrl = file.response.data;
     imgUrls.push(imgUrl)
   }
   weibo.value.imgUrls = imgUrls.toString();
 }
  let data = qs.stringify(weibo.value);
  axios.post("http://localhost:8080/v1/weibos/post",data)
      .then((response)=>{
        if(response.data.code = 2001) {
          ElMessage.success("成功发布评论");

        }else {
          ElMessage.error(response.data.msg);
        }
      })
}

const fileList = ref([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview= (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
      dialogVisible.value = true
}
</script>

<template>
<h1>发布评论功能</h1>
  <el-row :gutter="10">
   <el-col :span="12"><el-card><el-image src="/imgs/reg.png" style="width: 100%"></el-image></el-card></el-col>
    <el-col :span="12">
      <el-form style="margin-top: 200px">
<!--        上传图片开始-->
        <el-upload 
            style="margin-bottom: 10px"
            v-model:file-list="fileList"
            action="http://localhost:8080/v1/uploads/upload"
            name="file"
            limit="4"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
        >
          <el-icon ><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
        <!--        上传图片结束-->
        <el-form-item><el-input v-model="weibo.content" placeholder="请输入发布内容"></el-input></el-form-item>
        <el-form-item><el-button type="primary" style="margin: 0 auto"  @click="post">发布</el-button></el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style scoped>

</style>